﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Entities;
using hpcpdi.DataAccess.Interface;
using hpcpdi.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace hpcpdi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserRepository userRepository;
        private readonly ILogger logger;
        public UserController(IUserRepository _userRepository, ILoggerFactory logFactory)
        {
            userRepository = _userRepository;
            logger = logFactory.CreateLogger<UserController>();
        }

        [HttpGet("/api/user/getuser")]
        public async Task<ResultModel<User>> GetUser(string username, string pwd)
        {
            var user = await userRepository.GetUser(username, pwd);
            if (user != null)
            {
                logger.LogInformation(username + " login:success");
                return ResultModel.Success<User>(user);
            }
            else
            {
                logger.LogInformation(username + " login:失败");
                return ResultModel.Fail<User>(user);
            }
        }
        [HttpGet("/api/{id}")]
        public ActionResult<string> GetUserById(int id)
        {
            var redisResult = RedisClient.redisClient.GetStringKey<int>("key1");
            if (redisResult == default(int))
            {
                Console.WriteLine("redisResult is empty");
                RedisClient.redisClient.SetStringKey<int>("key1", id);
                return redisResult.ToString();
            }
            else
            {
                return redisResult.ToString();//有则直接返回
            }

        }
        /// <summary>
        /// 测试异常
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/user/sub")]
        public async Task<int> subException() {
            int a = 2;
            int b = 0;
            int j=await Task.Run(()=> a / b);

            return j;
        }
    }
}
